package com.lagou.rpc.consumer.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.Callable;

/**
 * 客户端处理类
 * 1.发送消息
 * 2.接收消息
 */
public class RpcClientHandler extends SimpleChannelInboundHandler<String> implements Callable {

    private ChannelHandlerContext chc;

    private String sendMsg;

    private String responseMsg;

    public void setSendMsg(String sendMsg) {
        this.sendMsg = sendMsg;
    }

    /**
     * 通道连接就绪事件
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        chc =ctx;
    }

    /**
     *  通道读取就绪事件
     * @param channelHandlerContext
     * @param msg
     * @throws Exception
     */
    @Override
    protected synchronized void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        responseMsg = msg;
        //唤醒等待的线程
        notify();
    }

    @Override
    public synchronized Object call() throws Exception {
        chc.writeAndFlush(sendMsg);//消息发送
        /*
           线程等待,等到服务端响应消息回来之后，会被上面的channelRead0()方法中的notify()方法唤醒，
           然后往下执行,将服务端的响应信息作为返回值返回。RpcClient类中的send方法中，通过线程池的get方法即可获得该返回值
         */
        wait();
        return responseMsg;
    }
}
